﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Runtime.Serialization;

namespace MvcFlow.Mvc
{
    [Serializable]
    public class HttpValueDictionary : Dictionary<string,string> 
    {
        public bool ValueEquals<T>(string key,T value)
        {
            string existingValue = null;
            if ( TryGetValue(key,out existingValue))
            {
                if( typeof(T) != typeof(string))
                {
                    return existingValue.Equals(value.ToString(), StringComparison.OrdinalIgnoreCase);
                }

                var convertedValue = Convert.ChangeType(existingValue, typeof (T));
                return convertedValue.Equals(value);
            }

            return false;
        }

        public HttpValueDictionary()
            : base(StringComparer.OrdinalIgnoreCase)
        {}

        public HttpValueDictionary(NameValueCollection valueCollection)
            : base(StringComparer.OrdinalIgnoreCase)
        {
            foreach( var key in valueCollection)
            {
                if ( !this.ContainsKey((string)key))
                {
                    this.Add((string)key,(string)valueCollection[(string)key]);
                }
            }
        }

        public HttpValueDictionary( IEnumerable<KeyValuePair<string,string>> values )
            : base(values.ToDictionary(v => v.Key,v => v.Value,StringComparer.OrdinalIgnoreCase),StringComparer.OrdinalIgnoreCase)
        {}

        protected HttpValueDictionary(SerializationInfo serializationInfo,StreamingContext streamingContext)
            : base(serializationInfo,streamingContext)
        {}
    }
}